#!/bin/bash -e
#   * compile instructions: put this file in
#   *         `steamapps/common/Dyson Sphere Program/CustomMod`
#   * folder, open a terminal in the same folder, and execute:
#   *
#   * ```
#   *     chmod +x ${file}.cs
#   *     ./${file}.cs
#   * ```
#   *
#   * then the mod will be compiled automatically.
#   *
#   * Here we wrote a shebang like file, which is correct
#   * in my computer (Manjaro XFCE), if such script do not work
#   * in your computer, you could just try the instructions below :

export IFS=$'\n' # to disable the annoying space.
export DOTNET=dotnet # the location of the DOTNET executable file.
[ -z "$DOTNET_CSC_DLL" ] && export DOTNET_CSC_DLL=`\ls /usr/share/dotnet/sdk/*/Roslyn/bincore/csc.dll` # In manjaro, the csc.dll is located in /usr/share/dotnet/sdk/*/Roslyn/bincore/csc.dll

__MODE_VERBOSE=82 # is the line number of "#define VERBOSE", may be modified
__MODE_DEBUG__=$((__MODE_VERBOSE+1))
__MODE_RELEASE=$((__MODE_DEBUG__+1))

case $1 in
    V)       _MODE__SELECT_=$__MODE_VERBOSE     ;;
    v)       _MODE__SELECT_=$__MODE_VERBOSE     ;;
    VERBOSE) _MODE__SELECT_=$__MODE_VERBOSE     ;;
    verbose) _MODE__SELECT_=$__MODE_VERBOSE     ;;
    D)       _MODE__SELECT_=$__MODE_DEBUG__     ;;
    d)       _MODE__SELECT_=$__MODE_DEBUG__     ;;
    DEBUG)   _MODE__SELECT_=$__MODE_DEBUG__     ;;
    debug)   _MODE__SELECT_=$__MODE_DEBUG__     ;;
    *)       _MODE__SELECT_=$__MODE_RELEASE     ;;
esac

# export GAME_NAME="${0%\.cs}" # now, file name should be equals to ${GAME_NAME}.cs, the benefit is, we could only change the name, rather than change filename and $GAME_NAME.
# export GAME_NAME="$(basename `pwd`)" # now, file name should be equals to ${GAME_NAME}.cs, the benefit is, we could only change the name, rather than change filename and $GAME_NAME.
export GAME_NAME="LearningFactory"
export FILE_NAME="$0"
export GAME_DIR="$GAME_NAME"                                # might be modified, "$GAME_NAME" cover most of the cases.
export ASSEMBLY="Assembly-CSharp"                           # might be modified
export UTILS="utils.cs"                                     # might be modified if you do not put utils.cs in the current dir.
export PLUGIN_ID="Neutron3529.Cheat"                        # should be modified
export NAMESPACE_ID="Neutron3529.Cheat"                     # should be modified
export GAME_BASE_DIR="common/$GAME_DIR"                     # should modify GAME_DIR instead since GAME_DIR == GAME_NAME is almost always true.

( yes "" | head -n $_MODE__SELECT_ | head -n-1  ; tail $FILE_NAME -n+$_MODE__SELECT_ ) | sed s/%%NAMESPACE_ID%%/${NAMESPACE_ID}/g | sed s/%%PLUGIN_ID%%/${PLUGIN_ID}/g | $DOTNET $DOTNET_CSC_DLL -nologo -t:library \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/0Harmony.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.Harmony.dll" \
  `[ -e "${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll" ] && echo "-r:\"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll\""` \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.Core.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.AIModule.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.CoreModule.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.UI.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/mscorlib.dll" \
  $(for i in "${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/$ASSEMBLY"*.dll ; do echo -e "-r:\"$i\"\n" ; done) \
  -out:"${GAME_BASE_DIR}/BepInEx/plugins/${FILE_NAME%.*}".dll \
  -optimize `[ "$_MODE__SELECT_" == "$__MODE_DEBUG__" ] && echo -debug` \
  $UTILS - && rm -f "${GAME_BASE_DIR}/BepInEx/config/${PLUGIN_ID}.cfg";

if [ -n "$2" ]; then
    git add ${FILE_NAME}
    case $2 in
        R) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        r) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        RANDOM) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        random) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        U) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        u) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        UPLOAD) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        upload) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        *) git commit -am "$2" ;;
    esac
    git push
fi
exit

#define VERBOSE // the line of __MODE_VERBOSE
#define DEBUG



using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;

using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

namespace LearnFactory
{
    [BepInPlugin("Neutron3529.Cheat", "LearnFactory", "0.1.0")]
    public class LearnFactory : BaseUnityPlugin {
        public static int speed_mul=60;
#if DEBUG
        public static Action<string> logger;
#endif
        void Start() {
            var harmony=new Harmony("Neutron3529.LearnFactory");
#if DEBUG
            logger=Logger.LogInfo;
            Neutron3529.Utils.Targets.logger=logger;
#endif
#if DEBUG
            logger("LearnFactory-开始注入");
#endif
            if ((speed_mul=Config.Bind<int>("config", "All_EndTick", 60, "工作速度乘数，大于1启用").Value)>1){
                harmony.PatchAll(typeof(All_EndTick)); // ResearchLab烧钱，且不会因为烧钱造成任何正面产出。
#if DEBUG
                logger("LearnFactory-注入ResourceBuildingEndTick - ResourceBuildingGetCurFertilityAdd");
#endif
                harmony.PatchAll(typeof(ResourceBuildingEndTick));
                harmony.PatchAll(typeof(ResourceBuildingGetCurFertilityAdd));
#if DEBUG
                logger("LearnFactory-研究站修正");
#endif
                harmony.PatchAll(typeof(ResearchLabTryGrabNewData));
                harmony.PatchAll(typeof(ResearcherAddExperience));
#if DEBUG
                logger("LearnFactory-增加工作速度-加载完成");
#endif
            }
            if (Config.Bind("config", "max_earning", true, "商店收益最大化").Value){
                harmony.PatchAll(typeof(ShopNormalPrice));
#if DEBUG
                logger("LearnFactory-商店收益最大化-加载完成");
#endif
            }
#if DEBUG
            logger("LearnFactory-加载完成");
#endif
        }

        [HarmonyPatch(typeof(ResourceBuilding), "EndTick")]
        static class ResourceBuildingEndTick{
            static void Prefix(ResourceBuilding __instance, ref float ___curFetility){
                ___curFetility = 1f;
            }
        }
        [HarmonyPatch(typeof(ResourceBuilding), "GetCurFertilityAdd")]
        static class ResourceBuildingGetCurFertilityAdd{
            static void Postfix(ref float __result){
                __result=1f;
            }
        }
        [HarmonyPatch(typeof(Shop), "NormalPrice")]
        static class ShopNormalPrice{
            static void Postfix(Shop __instance, ref int __result){
                __result=__instance.IsSideShop ? __instance.Customer.UpsaleMoney : __instance.Customer.Money;
            }
        }
        [HarmonyPatch(typeof(ResearchLab), "TryGrabNewData")]
        static class ResearchLabTryGrabNewData{
            static void Prefix(ResearchLab __instance){
                __instance.Researcher.MoneyPerArticle=0;
            }
        }
        [HarmonyPatch(typeof(Researcher), "AddExperience")]
        static class ResearcherAddExperience{
            static void Prefix(ref float totalValue){
                totalValue*=speed_mul;
            }
        }
        class All_EndTick : Neutron3529.Utils.Targets {
//             static new bool Prepare(MethodBase __originalMethod){
//                 return Neutron3529.Utils.Targets.Prepare(__originalMethod);
//             }
            static IEnumerable<MethodBase> TargetMethods()
            {
                Type[] t=typeof(Building).Assembly.GetTypes();
                foreach(Type ty in t){
                    MethodInfo[] m=ty.GetMethods();
                    foreach(MethodInfo i in m)if(i.Name=="EndTick"){
#if DEBUG
                        logger("LearnFactory-准备注入类别"+ty.ToString()+"的EndTick方法");
#endif
                        yield return i;
                    }
                }
            }
            static IEnumerable<CodeInstruction> Transpiler(MethodBase __originalMethod, IEnumerable<CodeInstruction> instructions) {
#if DEBUG
                logger("LearnFactory-正在注入类别"+__originalMethod.DeclaringType.Name+"的"+__originalMethod.Name+"方法");
#endif
                //return instructions;
                return new CodeMatcher(instructions)
                    .MatchForward(false, // false = move at the start of the match, true = move at the end of the match
                        new CodeMatch(OpCodes.Ldarg_0),
                        new CodeMatch(i=> i.opcode==OpCodes.Ldfld && ((FieldInfo)i.operand).Name == "Time"), // match method 2
                        new CodeMatch(OpCodes.Ldc_I4_1),
                        new CodeMatch(OpCodes.Add)
                    ).Repeat( matcher => // Do the following for each match
                        matcher
                        .Advance(2) // Move cursor to after ldfld
                        .SetAndAdvance(
                            OpCodes.Ldc_I4,speed_mul
                        )
                    ).InstructionEnumeration();
            }
        }
    }
}
